<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 输入框 -->
      <div>
        <el-row :gutter="20">
          <el-col :span="6"> <el-button type="primary" @click="addOpenDialog()">添加分类</el-button></el-col>
        </el-row>
      </div>
      <!-- 用户列表区 table -->
      <tree-table class="table-box" index-text="#" :data="cateList" :columns="columns" :selection-type="false" :expand-type="false" show-index border>
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" style="color:lightgreen" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" style="color:red" v-else></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag size="mini" type="success" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="info" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row.cat_id)">编辑</el-button>

          <!-- 删除 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="openDel(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!-- pagesize -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 6, 9]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- adddialog -->
      <el-dialog title="添加分类" :visible.sync="dialogaddVisible" width="50%" @close="addCateDialogClosed">
        <el-form :model="addForm" :rules="addrules" ref="addRef" label-width="100px">
          <el-form-item label="活动名称:" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类:">
            <el-cascader
              style="width:100%"
              clearable
              v-model="selectedKeys"
              :options="praentCateList"
              expandTrigger="hover"
              :props="propsCascader"
              change-on-select
              @change="parentCateChanged"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogaddVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑分类对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="closeDialogEdit()">
        <!-- edit dialog表单内容 -->
        <el-form :model="editForm" :rules="addrules" ref="editFormRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 3
      },
      cateList: [],

      total: 0,
      //   treeTable
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          // 表示，将当前列定义为模板列
          type: 'template',
          // 表示当前这一列使用模板名称
          template: 'opt'
        }
      ],
      dialogaddVisible: false,
      //   addform
      addForm: {
        //   将要添加的分类名称
        cat_name: '',
        // 分类父 ID
        cat_pid: 0,
        //  默认分类层级
        cat_level: 0
      },
      //   父级分类列表
      praentCateList: [],
      addrules: {
        cat_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 选中的父级分类的Id数组
      selectedKeys: [],
      propsCascader: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   编辑
      editForm: {},
      editDialogVisible: false
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      //   console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败!')
      }
      this.$message.success('获取商品分类数据列表成功!')
      this.cateList = res.data.result
      this.total = res.data.total
    },
    // pagesize改变
    handleSizeChange(newpagesize) {
      //   console.log(newpagesize)
      this.queryInfo.pagesize = newpagesize
      this.getCateList()
    },
    // 当前页改变
    handleCurrentChange(Currentpage) {
      //   console.log(Currentpage)
      this.queryInfo.pagenum = Currentpage
      this.getCateList()
    },
    // 打开addOpenDialog
    addOpenDialog() {
      this.getPraentCateList()
      this.dialogaddVisible = true
    },
    // 获取父级分类
    async getPraentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败!')
      }
      console.log(res.data)
      this.praentCateList = res.data
    },
    // 父级分类改变事件
    parentCateChanged() {
      console.log(this.selectedKeys)
      // 如果 selectedKeys 数组中的 length 大于0，证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的Id
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        // 为当前分类的等级赋值
        this.addForm.cat_level = this.selectedKeys.length
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    addCate() {
      //   console.log(this.addForm)
      this.$refs.addRef.validate(async (vaild) => {
        // console.log(vaild)
        if (!vaild) {
          return vaild
        }
        const { data: res } = await this.$http.post('categories', this.addForm)
        // console.log(res.data)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }

        this.$message.success('添加分类成功!')

        this.dialogaddVisible = false
        this.getCateList()
      })
    },
    // addCateDialogClosed 关闭事件
    addCateDialogClosed() {
      this.$refs.addRef.resetFields()
      this.selectedKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },
    // 关闭edit对话框并重置表单
    closeDialogEdit() {
      //   console.log(this.$refs)
      this.$refs.editFormRef.resetFields()
    },
    // 打开编辑对话框并根据id渲染form
    async openEditDialog(id) {
      this.editDialogVisible = true
      console.log(id)
      const { data: res } = await this.$http.get(`categories/+${id}`)
      //   console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('查询编辑分类失败!')
      }
      this.editForm = res.data
    },
    // 点击确定按钮编辑用户
    editUserInfo() {
      this.$refs.editFormRef.validate(async (vaild) => {
        if (!vaild) return vaild
        // console.log(vaild)
        const { data: res } = await this.$http.put(`categories/+${this.editForm.cat_id}`, {
          cat_name: this.editForm.cat_name
        })
        // console.log(res.data)
        if (res.meta.status !== 200) {
          return this.$message.error('编辑分类失败!')
        }
        this.editDialogVisible = false
        this.$message.success('编辑分类成功!')
        this.getCateList()
      })
    },
    // 点击确定按钮删除用户
    async openDel(id) {
      // console.log(id)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      console.log(confirmResult)
      // 如果用户确认删除返回结果为字符串confirm
      // 如果用户取消删除返回结果为字符串cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // console.log('queren')
      const { data: res } = await this.$http.delete(`categories/+${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败!')
      }
      this.$message.success('删除分类成功!')
      this.getCateList()
    }
  },
  created() {
    this.getCateList()
  }
}
</script>

<style lang="scss" scoped>
.table-box {
  margin-top: 15px;
}
</style>
